import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    const { data } = response
    if (data.code === 200) {
      return data
    } else {
      ElMessage.error(data.msg || '请求失败')
      return Promise.reject(new Error(data.msg || '请求失败'))
    }
  },
  error => {
    if (error.response?.status === 401) {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
      window.location.href = '/login'
    }
    ElMessage.error(error.message || '网络错误')
    return Promise.reject(error)
  }
)

// 登录API
export const login = (data) => {
  return api.post('/auth/login', data)
}

// 报修相关API
export const submitRepair = (data) => {
  return api.post('/repair/submit', data)
}

export const getMyRepairs = () => {
  return api.get('/repair/my')
}

export const getAssignedRepairs = () => {
  return api.get('/repair/assigned')
}

export const getAllRepairs = () => {
  return api.get('/repair/all')
}

export const updateRepair = (data) => {
  return api.put('/repair/update', data)
}

export const deleteRepair = (id) => {
  return api.delete(`/repair/${id}`)
}

// 后勤人员管理API
export const getAllLogisticsStaff = () => {
  return api.get('/logistics-staff/all')
}

export const addLogisticsStaff = (data) => {
  return api.post('/logistics-staff/add', data)
}

export const updateLogisticsStaff = (data) => {
  return api.put('/logistics-staff/update', data)
}

export const deleteLogisticsStaff = (id) => {
  return api.delete(`/logistics-staff/${id}`)
} 